#include "logging.h"

#include <stdlib.h>
#include <stdio.h>

static const char *config_path_env_variable = "SCRAPPER_BOT_CONFIG_PATH";
static const char *config_path = "telegram_bot_web_scrapper.conf";

struct logging_categories
{
  zlog_category_t *category_bot[logging_category_end];
};

__attribute__((always_inline)) inline static void
handle_category_error (const zlog_category_t * const category)
{
  if (!category)
    {
      fprintf (stderr, "couldn't create category\n");
      zlog_fini();
      exit (EXIT_FAILURE);
    }
}

__attribute__((always_inline)) inline static void
handle_init_error (int return_code, const char *config)
{
  if (return_code)
    {
      fprintf (stderr, "logger init failed: %s\n", config);
      exit (EXIT_FAILURE);
    }
}

static void
initialize_categories (void)
{
  static struct logging_categories logging_categories;
  for_each_enum(category, logging_category)
  {
    zlog_category_t *zc =
      zlog_get_category (logging_category_to_string (category));
    handle_category_error (zc);
    logging_categories.category_bot[category] = zc;
  }
}

__attribute__((constructor)) static void
initialize (void)
{
  const char *config = getenv(config_path_env_variable);
  if (!config)
    config = config_path;

  int rc = zlog_init (config);
  handle_init_error (rc, config);
  initialize_categories ();
}

__attribute__((destructor)) static void
deinitialize (void)
{
  zlog_fini();
}
